#include <QtOpenGL>
#include "glext.h"
#include "water.h"

Water::Water(const QGLContext* context)
{
	if(0 == glActiveTextureARB)
		glActiveTextureARB  = (void (APIENTRY *) (GLenum)) context->getProcAddress("glActiveTextureARB");
}

bool Water::loadTextures( QGLWidget* glwidget )
{
	if(!glwidget)
		return false;

	normalMap = glwidget->bindTexture(QImage("./water/waves.jpg"));
	return true;
}

bool Water::loadShaders()
{
	bool result = shader.addShaderFromSourceFile(QGLShader::Vertex, "./shaders/water.vert");
	result &= shader.addShaderFromSourceFile(QGLShader::Fragment, "./shaders/water.frag");
	result &= shader.link();

	return result;
}

void Water::draw(const ShipRenderData& mathModel,const std::vector<float>& lookFrom, const GLuint shadowMap)
{
	if (lookFrom.size() != 3)
		return;

	shader.bind();
	shader.setUniformValue("time", GLfloat(mathModel.timeStamp));
	shader.setUniformValue("centerX", GLfloat(mathModel.x));
	shader.setUniformValue("centerY", GLfloat(mathModel.y));
	glActiveTextureARB(GL_TEXTURE0_ARB);
	glBindTexture(GL_TEXTURE_2D, normalMap);
	shader.setUniformValue("NormalMap", 0);
	shader.setUniformValue("eyePosition", lookFrom[0],
													lookFrom[1],
													lookFrom[2]);
	shader.setUniformValue("WavePeriod", GLfloat(4.0));
	glPushMatrix();

	for(float x = -40.0; x <= 39.8; x += 0.2)
	{
		glBegin(GL_TRIANGLE_STRIP);
		for(float z = -40.0; z <= 39.8; z += 0.2)
		{
			glVertex3f(x + 0.2, 0.0, z);
			glVertex3f(x, 0.0, z);
			
		}
		glEnd();
	}

	glPopMatrix();

	glActiveTextureARB(GL_TEXTURE0_ARB);
}
